package com.heima.user.service.Imp;

import com.heima.common.exception.CustException;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.UserRelationDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     *用户关注关联关系
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //1.校验参数是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"当前未登录！");
        }
        //2.判断operation 的参数是否是0  代表关注请求
        Short operation = dto.getOperation();
        if (operation != 0 && operation != 1) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"取关传参错误");
        }
        Integer authorApUserId = dto.getAuthorApUserId();
        Integer userId = user.getId();
        if (operation == 0) {
            //校验 不能重复关注 查询用户是否关注
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId));
            if (score != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"不可重复关注作者");
            }
            //校验 不能自己关注自己
            if (authorApUserId == userId) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能自己关注自己哦");
            }
            //在当前用户关注的集合中，加入作者的apuser的id
            //用户关注关系
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + userId,
                    String.valueOf(authorApUserId),
                    System.currentTimeMillis());
            //添加作者粉丝关系
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + authorApUserId,
                    String.valueOf(userId),
                    System.currentTimeMillis());
        }else {
            //3.判断operation的值是否为1 代表取消关注请求

            //当前登陆用户的关注集合 删除作者对应的apuser的id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + userId ,String.valueOf(authorApUserId));
            //在作者对应的粉丝集合中删除对应的登陆用户的id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorApUserId ,String.valueOf(userId));
        }
        return ResponseResult.okResult();
    }


}
